<?php
/**
 * 客服功能api 2018-09-25
 */
namespace app\api\controller;

use think\Db;
use app\common\model\Bespeak as BespeakModel;
use app\common\model\Csuser as CsuserModel;
use app\common\model\Users as UsersModel;
use app\common\model\AuthorWxUser as AuthorWxUserModel;
use app\common\model\UsersAdded as UsersAddedModel;
use app\common\model\WxUser as WxUserModel;
use app\common\util\WechatThirdUtil;

class CustomerService extends Base
{
    protected $csuser_model;
    protected $users_model;
    protected $users_added_model;
    protected $config;
    protected $wx_user;
    protected $bespeak_model;
    protected $wechatObj;
    private $request_uri;
    private $author_wx_user_model;

    protected function _initialize(){
        parent::_initialize();
        $this->request_uri = NODE_URL.'/receiveMsg';
        $this->bespeak_model = new BespeakModel();
        $this->wx_user = new WxUserModel();
        $this->config = $this->wx_user->find();
        $this->csuser_model = new CsuserModel();
        $this->users_model = new UsersModel();
        $this->users_added_model = new UsersAddedModel();
        $this->author_wx_user_model = new AuthorWxUserModel();
    }

    /**
     * 获取客服信息
     * @param type id
     */
    public function getCustmerServiceInfo(){
        $id = $this->request->post('id');
        $where = ['id' => ['eq',$id],];
        $result = $this->csuser_model->field('id,username,nickname,header_url,wechatnum,online_butt,today_butt,status,type,create_time')->where($where)->find();
        if($result){
            return $this->buildSuccess(['status' => 1 , 'msg' => '获取成功', 'cs_info' => $result]);
        }else{
            return json(['status' => -1 , 'error' => 'Unable to obtain information']);
        }
    }

    /**
     * 获取客服下的客户列表
     * @param type butt_id 客服id
     */
    public function getButtInfo(){
        $id = $this->request->post('butt_id');
        if(!empty($butt_id)){
            $csuser_info = $this->csuser_model->field('auid,pid')->where('id',$butt_id)->find();
            if($csuser_info['pid'] == 0){
                $cs_ids = $this->csuser_model->where('pid',$butt_id)->column('id');
                array_push($cs_ids,(int)$butt_id);
                $result = $this->users_model
                        ->alias('u')
                        ->whereIn('butt_id',$cs_ids)
                        ->join('think_users_added','think_users_added.uid = u.user_id','LEFT')
                        ->order('last_butt_time desc,user_id desc')
                        ->select();
            }else{
                $result = $this->users_model
                        ->alias('u')
                        ->where('butt_id',$butt_id)
                        ->join('think_users_added','think_users_added.uid = u.user_id','LEFT')
                        ->order('last_butt_time desc,user_id desc')
                        // ->limit(500)
                        ->select();
            }
            return $this->buildSuccess(['status'=> 1,'msg'=>'获取成功' , 'cs_userList' => $result]);
        }else{
            return json(['status'=> 0,'msg'=>'错误']);
        }
    }

    /**
     * 加载更多(获取客服下的客户列表)
     * @param type butt_id 客服id
     * @param type offset 偏移量
     */
    public function getButtInfoMore($butt_id,$offset){
            $data = $this->request->post();
            $butt_id = $data['butt_id'];
            $offset = $data['offset'];
            $csuser_info = $this->csuser_model->field('auid,pid')->where('id',$butt_id)->find();
            if ($csuser_info) {
                if($csuser_info['pid'] == 0){
                    $result = $this->users_model
                            ->alias('u')
                            ->where('auid',$csuser_info['auid'])
                            ->join('think_users_added','think_users_added.uid = u.user_id','LEFT')
                            ->order('last_butt_time desc,user_id desc')
                            ->limit($offset,30)
                            ->select();
                }else{
                    $result = $this->users_model
                            ->alias('u')
                            ->where('butt_id',$butt_id)
                            ->join('think_users_added','think_users_added.uid = u.user_id','LEFT')
                            ->order('last_butt_time desc,user_id desc')
                            ->limit($offset,30)
                            ->select();
                }
                return $this->buildSuccess(['status'=> 1,'msg'=>'获取成功' , 'cs_more_userList' => $result]);
            } else {
                return json(['status'=> -1,'msg'=>'获取失败']);
            }
            
            
    }

    /**
     * 获取当前在线客服列表
     * @param type auid
     */
    public function getCustmerServiceList(){
        $auid = $this->request->post('auid');
        $where = [
            'auid' => ['eq',$auid],
            'status' => ['eq',1],
            'type' => ['eq',1]
        ];
        $result = $this->csuser_model->field('id,username,nickname,header_url')->where($where)->select();
        if($result){
            return $this->buildSuccess(['status' => 1 , 'msg' => 'ok', 'cs_currentList' => $result]);
        }else{
            return json(['status' => -1 , 'error' => 'Unable to obtain information']);
        }
        
    }

    /**
     * 转接客服
     * @param type opneid
     * @param type butt_id //已对接客服id
     * @param type cs_id //需要转接的客服id
     */
    public function moveCustmerService(){
        $data = $this->request->post();
        $openid = $data['openid'];
        $butt_id = $data['butt_id'];
        $cs_id = $data['cs_id'];
        $where = [
            'openid' => ['eq',$openid],
            'butt_id' => ['eq',$butt_id]
        ];
        $result = $this->users_model->save(['butt_id' => $cs_id],$where);
        if($result){
            return $this->buildSuccess(['status' => 1 , 'msg' => '转接成功']);
        }else{
            return json(['status' => -1 , 'error' => '转接失败']);
        }
    }

    /**
     * 保存用户额外信息
     * @param type uid //用户id
     * @param type wechat_num //用户微信号
     * @param type name //用户姓名
     * @param type remark //备注
     * @param type phone //用户联系方式
     * @param type age //用户年龄
     */
    public function saveUserOtherMsg(){
            $data = $this->request->post();
            if(!isset($data['uid']) || empty($data['uid'] || !$this->users_model->where('user_id',$data['uid'])->find())){
                return json(['status' => -1 , 'error' => '参数错误']);
            }
            if($this->users_added_model->where('uid',$data['uid'])->find()){
                $result = $this->users_added_model->save($data,['uid' => $data['uid']]);
            }else{
                $result = $this->users_added_model->allowField(true)->save($data);
            }
            
            if($result){
                $user_info = $this->users_model->alias('u')->where('user_id',$data['uid'])->join('think_users_added','think_users_added.uid = u.user_id')->find();
                return $this->buildSuccess(['status' => 1 , 'msg' => '保存成功' , 'user_info' => $user_info]);
            }else{
                return json(['status' => -1 , 'error' => '保存失败']);
            }
    }

    /**
     * 获取所有客服
     * @param type auid
     */
    public function getAllCustmerService(){
        $auid = $this->request->post('auid');
        $where = [
            'auid' => ['eq',$auid]
        ];
        $result = $this->csuser_model->field('id,username,nickname,header_url,type,status')->where($where)->select();
        if($result){
            return $this->buildSuccess(['status' => 1 , 'msg' => '获取成功', 'cs_allList' => $result]);
        }else{
            return json(['status' => -1 , 'error' => 'Unable to obtain information']);
        }
    }

    /**
     * 获取客服接线状态
     * @param type cs_id
     */
    public function getConnectLink(){
        $cs_id = $this->request->post('cs_id');
        $status = $this->csuser_model->where('id',$cs_id)->value('status');
        if($status !== false){
            return $this->buildSuccess(['status' => 1 , 'msg' => '获取成功' , 'cs_buttStatus' => $status]);
        }else{
            return json(['status' => -1 , 'error' => 'mistake param']);
        }
    }

    /**
     * 设置离线回复
     * @param type id 客服id
     * @param string auto_reply_img 回复图片
     * @param string auto_reply_text 回复文本
     */
    public function saveReply(){
        $data = $this->request->post();
        $id = $data['id'];
        $csuser = $this->csuser_model->field('auid,auto_reply_img')->where('id',$id)->find();
        $auto_reply_img = $csuser['auto_reply_img'];
        $author_wx = $this->author_wx_user_model->where('id',$csuser['auid'])->where('authorized',1)->find();
        if($author_wx){
            $wechatObj = new WechatThirdUtil($this->config , $author_wx);
            if($auto_reply_img != $data['auto_reply_img'] && !empty($data['auto_reply_img'])){
                //图片非空应上传到微信资源
                $chatImg = $wechatObj->uploadMaterial('.'.$data['auto_reply_img'],'image');
                if($chatImg){
                    $data['auto_reply_img_media_id'] = $chatImg['media_id'];
                }else{
                    return json(['status' => -1 , 'error' => 'upload wechat error']);
                }
            }
            $result = $this->csuser_model->save($data,['id'=>$id]);
            if($result){
                return $this->buildSuccess(['status' => 1 , 'msg' => '保存成功']);
            }else{
                return json(['status' => -1 , 'error' => 'repeat edit or error']);
            }
        }else{
            return json(['status' => -1 , 'error' => 'the publicnum unauthor']);
        }
    }

    /**
     * 获取离线回复
     */
    public function getReply(){
        $id = $this->request->post('id');
        $result = $this->csuser_model->field('auto_reply_text,auto_reply_img')->where('id',$id)->find();
        if($result){
            return $this->buildSuccess(['status' => 1 , 'msg' => '获取成功' ,'cs_replyInfo' => $result]);
        }else{
            return json(['status' => -1 , 'error' => 'error']);
        }
    }

    /**
     * 客服发送离线消息
     * @param openid 用户openid
     * @param butt_id 客服id
     */
    public function outlineMsg(){
        $outlineReply = [];
        $data = $this->request->post();
        $openid = $data['openid'];
        $butt_id = $data['butt_id'];
        $sqlname = 'chatlog'.$butt_id % 10;
        $csuser = $this->csuser_model->alias('c')->field('c.type,c.auto_reply_text,c.auto_reply_img,c.auto_reply_img_media_id,a.id,a.appid')
                    ->where('c.id',$butt_id)->join('think_author_wx_user a','a.id = c.auid')->find();
        $author_wx = ['id' => $csuser['id'] , 'appid' => $csuser['appid']];
        $this->wechatObj = new WechatThirdUtil($this->config , $author_wx);
        //且发送客服设置的离线消息

        if(!empty($csuser['auto_reply_text'])){
            $content = html_entity_decode($csuser['auto_reply_text']);
            $sendMsg = $this->wechatObj->sendMsgToOne($openid,$content);
            if($sendMsg){
                $outlineReply[] = [
                    'type'    => 'text',
                    'content' => $content, //消息文本
                    'openid'  => $openid, //用户openid
                    'appid'   => $author_wx['appid'], //对应公众号appid
                    'cs_id'   => $butt_id, //客服id
                    'send_time' => time(), //发送时间
                    'send_type' => '1002',
                    'needsend' => 0,
                ];
            }else{
                return json(['status' => -1 , 'error' => 'send text error']);
            }
        }

        
        if(!empty($csuser['auto_reply_img'])){
            $sendImg = $this->wechatObj->sendMediaToOne($openid,$csuser['auto_reply_img_media_id'],'image');
            if($sendImg){
                $outlineReply[] = [
                    'type'    => 'image',
                    'content' => $csuser['auto_reply_img'], //图片路径
                    'openid'  => $openid, //用户openid
                    'appid'   => $author_wx['appid'], //对应公众号appid
                    'cs_id'   => $butt_id, //客服id
                    'send_time' => time(), //发送时间
                    'send_type' => '1002',
                    'needsend' => 0,
                ];
            }else{
                return json(['status' => -1 , 'error' => 'send image error']);
            }
        }
        
        foreach($outlineReply as $v){
            $send_result = $this->send($this->request_uri, $v);
            if(!$send_result) return false;
        }

        if(!empty($outlineReply)){
            $result = Db::connect('db_config_chatlog')->name($sqlname)->insertAll($outlineReply);
            if(!$result) return json(['status' => -1 , 'error' => 'save chatlog error']);
            return $this->buildSuccess(['status' => 1 , 'msg' => '发送成功']);
        }else{
            return json(['status' => -1 , 'error' => 'not outline reply msg']);
        }
    }

    /**
     * 发送消息
     */
    private function send($url, $post_arr){
        $result = httpRequest($url,'POST',$post_arr);
        if(!$result) return false;
        return $result;
    }

    /**
     * --- 预约邀请 --- 
     */

    /**
     * 获取预约邀请列表
     * @param cs_id 客服id
     * @param openid 用户openid
     * @param type 类型
     * @param send_status 发送状态
     * @param limit 显示条数
     */
    public function bespeakList(){
            $limit = '';
            $data = $this->request->post();
            $where = [
                'cs_id' => ['eq',$data['cs_id']],
                'openid' => ['eq',$data['openid']],
            ];
            if(isset($data['type']) && !empty($data['type'])) $where['type'] = ['eq',$data['type']];

            if(isset($data['send_status']) && !empty($data['send_status'])) $where['send_status'] = ['eq',$data['send_status']];

            $limit = isset($data['limit']) && !empty($data['limit']) ? $data['limit'] : '';
            
            $this->bespeak_model = new BespeakModel();
            $result = $this->bespeak_model->where($where)->order('send_time DESC,create_time DESC')->limit($limit)->select();
            if(!$result) return json(['status' => -1 , 'error' => 'save bespeak error']);
            return $this->buildSuccess(['status' => 1 , 'msg' => '获取成功' , 'cs_bespeakList' => $result]);
    }

    /**
     * 保存预约消息
     * @param cs_id 客服id
     * @param openid 用户openid
     * @param type 类型
     * @param content 内容
     * @param image 图片
     * @param vedio 视频
     * @param voice 语音
     * @param news 图文
     */
    public function saveBespeak(){
        $data = $this->request->post();
        $validate_result = $this->validate($data,'bespeak');
        if($validate_result !== true){
            return json(['status' => -1 , 'error' => 'validate error' , 'result' => $validate_result]);
        }else{
            $data['create_time'] = time();
            $result = $this->bespeak_model->field(true)->insertGetId($data);
            if(!$result) return json(['status' => -1 , 'error' => 'save bespeak error']);
            return $this->buildSuccess(['status' => 1 , 'msg' => '保存成功' ,'id' => $result]);
        }
    }

    /**
     * 发送预约消息
     * @param id 预约id
     */
    public function sendBespeak(){
        $id = $this->request->post('id');
        $bespeak_result = $this->bespeak_model->where('id',$id)->find();
        $sqlname = 'chatlog'.$bespeak_result['cs_id'] % 10;
        $author_wx = $this->csuser_model->alias('c')->field('a.id as id,a.appid as appid,a.authorizer_refresh_token as authorizer_refresh_token')
                                        ->where('c.id',$bespeak_result['cs_id'])
                                        ->where('a.authorized',1)
                                        ->join('think_author_wx_user a','a.id = c.auid')
                                        ->find();
        $this->wechatObj = new WechatThirdUtil($this->config , $author_wx);
        if ($bespeak_result['type'] == 1) {
            //文本消息
            $butt_id = $bespeak_result['cs_id'];
            $openid = $bespeak_result['openid'];
            $content = $bespeak_result['content'];
            $sendMsg = $this->wechatObj->sendMsgToOne($openid , $content);

            
            $post_arr = [
                'type'    => 'text',
                'content' => $content, //消息文本
                'openid'  => $openid, //用户openid
                'appid'   => $author_wx['appid'], //对应公众号appid
                'cs_id'   => $butt_id, //客服id
                'send_time' => time(), //发送时间
                'send_type' => '1002',
            ];

        } else if ($bespeak_result['type'] == 2) {
            //图片消息
        } else if ($bespeak_result['type'] == 3) {
            //图文消息
        } else if ($bespeak_result['type'] == 4) {
            //语音消息
        } else if ($bespeak_result['type'] == 5) {
            //视频消息
        }

        if($sendMsg){
            $send_result = $this->send($this->request_uri, $post_arr);
            if(!$send_result) return false;

            $cs_type = $this->csuser_model->where('id',$butt_id)->value('type');
            
            if($cs_type == 3){
                $post_arr['needsend'] = 1;
            }else{
                $post_arr['needsend'] = 0;
            }

            if(!empty($post_arr)){
                $update_result = $this->bespeak_model->where('id',$id)->update(['send_status' => 2]);
                $result = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
                if(!$result || !$update_result) return json(['status' => -1 , 'error' => 'save chatlog error']);
                return $this->buildSuccess(['status' => 1 , 'msg' => '发送成功']);
            }
        }
    }

    
}